package com.buddha.api.service.impl;

import com.buddha.api.dto.MenuDto;
import com.buddha.api.entity.Menu;
import com.buddha.api.entity.User;
import com.buddha.api.mapper.MenuMapper;
import com.buddha.api.mapper.UserMapper;
import com.buddha.api.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2023-07-06
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Lazy
    @Autowired
    UserServiceImpl userService;

    @Autowired
    UserMapper userMapper;

    @Override
    public List<MenuDto> getCurrentUserNav() {
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userService.findByUsername(username);
        List<Long> menuIds = userMapper.selectMenuIds(user.getId());
        List<Menu> menus = listByIds(menuIds);
        List<Menu> menuTree = buildTreeMenu(menus);
        return convert(menuTree);
    }

    private List<MenuDto> convert(List<Menu> menuTree) {
        List<MenuDto> menuDtos = new ArrayList<>();
        menuTree.forEach(m -> {
                    MenuDto dto = new MenuDto();
                    dto.setId(m.getId());
                    dto.setPath(m.getPath());
                    dto.setName(m.getPerms());
                    dto.setTitle(m.getName());
                    dto.setComponent(m.getComponent());
                    dto.setIcon(m.getIcon());
                    if (m.getChildren().size() > 0){
                        dto.setChildren(convert(m.getChildren()));
                    }
                    menuDtos.add(dto);
                }
        );
        return menuDtos;
    }

    private List<Menu> buildTreeMenu(List<Menu> menus) {
        List<Menu> finalMenus = new ArrayList<>();
        for (Menu menu : menus) {
            for (Menu e : menus) {
                if (e.getParentId() == menu.getId()){
                    menu.getChildren().add(e);
                }
            }
            if (menu.getParentId() == 0L){
                finalMenus.add(menu);
            }
        }

        return finalMenus;
    }

    public List<Menu> tree() {
        List<Menu> list = this.list();
        return buildTreeMenu(list);
    }
}
